package com.module.circle.ui.taskRanking

import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.common.app.data.bean.circle.CirclesRankMyRankingBean
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.setVisibility
import com.common.base.app.extras.showToast
import com.common.base.app.extras.yes
import com.common.base.app.fragment.BaseVMFragment
import com.common.base.utils.DividePageUtils
import com.common.base.utils.Page
import com.common.base.widget.animator.CustomAnimation1
import com.module.circle.R
import com.module.circle.databinding.CircleFragmentTaskRankingBinding
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/07/30
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class TaskRankingFragment :
    BaseVMFragment<CircleFragmentTaskRankingBinding, CircleTaskRankingViewModel>() {

    private val classicsFooter by lazy { ClassicsFooter(requireActivity()) }

    private val mAdapter by lazy { TaskRankingListAdapter() }

    companion object {
        fun newInstance(mType: String, mId:Int): TaskRankingFragment {
            val fragment = TaskRankingFragment()
            fragment.mType = mType
            fragment.mId = mId
            return fragment
        }
    }

    private var mType: String = ""

    private var mId: Int = 0


    private val listTotal = ArrayList<CirclesRankMyRankingBean>()
    private var listPageUtil: DividePageUtils? = null

    /**
     * 分页
     */
    private val page = Page()

    private lateinit var headView: View

    override fun getPlaceholderView() = mViewBinding.placeView

    override fun getViewModel() = CircleTaskRankingViewModel::class.java

    override fun getViewBinding() = CircleFragmentTaskRankingBinding.inflate(layoutInflater)

    override fun initViews() {
        super.initViews()

        headView = layoutInflater.inflate(R.layout.circle_task_ranking_head_layout, null)

        //上下拉刷新
        getRefreshFooter()?.let { mViewBinding.pdView.setRefreshFooter(it) }
        mViewBinding.pdView.setRefreshHeader(
            ClassicsHeader(requireActivity()).setAccentColor(
                ContextCompat.getColor(requireActivity(), R.color.text_content_week)
            )
        )
        classicsFooter.setAccentColor(
            ContextCompat.getColor(
                requireActivity(),
                R.color.color_999999
            )
        )
        mViewBinding.pdView.setRefreshFooter(classicsFooter)

        mAdapter.apply {
            mAdapter.addHeaderView(headView)
            mAdapter.addFooterView(layoutInflater.inflate(R.layout.circle_task_ranking_footer_layout, null))
            adapterAnimation = CustomAnimation1()
            isAnimationFirstOnly = true
//            isAnimationFirstOnly = false
            mViewBinding.hrv.adapter = this
        }

    }

    override fun lazyInitData() {
        super.lazyInitData()
        mViewBinding.pdView.setEnableLoadMoreWhenContentNotFull(true)
        mViewBinding.pdView.setEnableLoadMore(true)
        getCirclesTaskRank(when(mType){
            getString(R.string.circle_movement_distance_hint)->"distance"
            getString(R.string.circle_running_pace_hint)->"pace"
            else->"days"
        })
        headView.findViewById<TextView>(R.id.tvHdCompletionDaysHint).text = when (mType) {
            getString(R.string.circle_movement_distance_hint) -> getString(R.string.circle_completion_distance_hint)
//                getString(R.string.circle_running_pace_hint) -> "pace"
            else -> getString(R.string.circle_completion_days_hint)
        }
    }


    override fun initEvents() {
        super.initEvents()
        setErrorRetryListener {
            lazyInitData()
        }

        mViewBinding.pdView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                lazyInitData()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                (mAdapter.data.size ==listTotal.size).yes {
                    mViewBinding.pdView.setEnableLoadMoreWhenContentNotFull(false)
                    mViewBinding.pdView.finishLoadMoreWithNoMoreData()
                }.otherwise {
                    listPageUtil = DividePageUtils(15, listTotal.size, page.pageNo)
                    val start = listPageUtil?.getFromIndex() //从哪开始
                    val end = listPageUtil?.getToIndex() //到哪结束
                    mAdapter.data.addAll(listTotal.subList(start?:0, end?:0))
                    mAdapter.notifyDataSetChanged()
                    finishPdView()
                    page.next()
                    page.loadSucc()
                }
            }
        })

//        mViewContentBinding.tvLoginOut.setOnClickListener(onClick = this)
    }

    private fun finishPdView() {
        mViewBinding.pdView.finishRefresh()
        mViewBinding.pdView.finishLoadMore()
    }


    private fun getCirclesTaskRank(type:String = "days") {
        if (mId<=0){
            showErrorMsg()
            return
        }
        showDialogLoading()
        mViewModel.getCirclesTaskRank(mId, type){
            finishPdView()
        }.observe(this) {
            finishPdView()
            dismissLoadingDialog()
            it.isSuccess().yes {
                it.isSuccess().yes {
                    it.Data?.let{ dataIt->
                        listTotal.clear()
                        page.reset()
                        dataIt.rankings?.let { it1 -> listTotal.addAll(it1) }
                        listPageUtil = DividePageUtils(15, listTotal.size, page.pageNo)
                        val start = listPageUtil?.getFromIndex() //从哪开始
                        val end = listPageUtil?.getToIndex() //到哪结束
                        mAdapter.setList(listTotal.subList(start?:0, end?:0))
                        page.next()
                        page.loadSucc()
                        setVisibility(mViewBinding.hrv, !listTotal.isNullOrEmpty())
                        listTotal.isNullOrEmpty().yes { showEmpty(getString(R.string.base_no_data2)) }.otherwise { showContent() }
                    }
                }.otherwise {
                    showToast(it.Message)
                }
            }.otherwise {
                showToast(it.Message)
            }
        }
    }
}